<template>
  <div :key="vueRest" class="addBrand-container">
    <div :key="restKey" class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm"
      >
        <div>
          <el-form-item label="菜品名称:" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请填写菜品名称"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="默认价格:" prop="defaultPrice">
            <el-input v-model="ruleForm.defaultPrice" readonly />
          </el-form-item>
          <el-form-item label="材料分类:" prop="materialId">
            <div v-for="(item, index) in ruleForm.dishInfoVOS" :key="index">
              <el-select v-model="item.materialId" placeholder="请选择材料分类">
                <el-option
                  v-for="(category, i) in setMealList"
                  :key="i"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
              <el-input
                v-model="item.materialNumber"
                placeholder="请填写材料克数"
                :min="1"
                :max="999"
                :step="1"
              />
              <el-button @click="removeMaterial(index)">❌</el-button>
              <el-form-item label="" prop="isMain">
                <el-switch
                  v-model="item.isMain"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是主食"
                  inactive-text="不为主食"
                />
              </el-form-item>
            </div>
            <el-button @click="addMaterial">添加材料</el-button>
          </el-form-item>
          <el-form-item label="菜品分类:" prop="typeId">
            <el-select
              v-model="ruleForm.typeId"
              placeholder="请选择菜品分类"
              @change="$forceUpdate()"
            >
              <el-option
                v-for="(item, index) in MealList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="折扣:" prop="discount">
            <el-input
              v-model="ruleForm.discount"
              placeholder="请设置菜品折扣"
            />
          </el-form-item>

          <el-form-item label="售卖状态:" prop="status">
            <el-switch
              v-model="ruleForm.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="售卖中"
              inactive-text="已下架"
            />
          </el-form-item>
          <el-form-item label="推荐状态:" prop="recommended">
            <el-switch
              v-model="ruleForm.recommended"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="推荐"
              inactive-text="不推荐"
            />
          </el-form-item>
          <el-form-item label="菜品描述:" prop="description">
            <el-input
              v-model="ruleForm.description"
              type="textarea"
              size="medium"
              :rows="3"
              maxlength="200"
              placeholder="菜品描述，最长200字"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="菜品图片:" prop="image">
            <image-upload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br />仅能上传 PNG JPEG JPG类型图片<br />建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-button @click="() => $router.back()">取消</el-button>
          <el-button
            type="primary"
            :class="{ continue: actionType === 'add' }"
            @click="submitForm('ruleForm')"
            >保存</el-button
          >
          <el-button
            v-if="actionType == 'add'"
            type="primary"
            @click="submitForm('ruleForm', 'goAnd')"
            >保存并继续添加</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import SelectInput from './components/SelectInput.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'

import {
  queryDishById,
  addDish,
  editDish,
  dishNoCategoryList,
  dishNoCategory,
} from '@/api/dish'
import { baseUrl } from '@/config.json'
import { getToken } from '@/utils/cookies'
@Component({
  name: 'addShop',
  components: {
    HeadLable,
    SelectInput,
    ImageUpload,
  },
})
export default class extends Vue {
  [x: string]: any
  private restKey: number = 0
  private textarea: string = ''
  private value: string = ''
  private setMealList: [] = []
  private MealList: [] = []
  private imageUrl: string = ''
  private actionType: string = ''
  private dishList: string[] = []
  private vueRest = '1'
  private index = 0
  private inputStyle = { flex: 1 }
  private headers = {
    token: getToken(),
  }
  private ruleForm = {
    id: '',
    name: '',
    price: '',
    image: '',
    description: '',
    discount: '',
    typeId: '',
    status: false,
    recommended: false,
    dishInfoVOS: [
      {
        deleted: 0,
        dishId: 0,
        id: 0,
        isMain: false,
        materialId: null,
        materialNumber: null,
      },
    ],
  }
  addMaterial() {
    this.ruleForm.dishInfoVOS.push({
      deleted: 0,
      dishId: 0,
      id: 0,
      isMain: false,
      materialId: null,
      materialNumber: null,
    })
  }

  removeMaterial(index: number) {
    this.ruleForm.dishInfoVOS.splice(index, 1)
  }

  get rules() {
    return {
      name: [
        {
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入菜品名称'))
            } else {
              const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
              if (!reg.test(value)) {
                callback(new Error('菜品名称输入不符，请输入2-20个字符'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur',
        },
      ],
      // categoryId: [
      //   { required: true, message: '请选择菜品分类', trigger: 'change' }
      // ],
      image: {
        required: true,
        message: '菜品图片不能为空',
      },
    }
  }

  created() {
    this.getDishList()
    this.getDishCategoryList()
    this.actionType = this.$route.query.id ? 'edit' : 'add'
    if (this.actionType == 'edit') {
      this.init()
    }
  }
  private async init() {
    queryDishById(this.$route.query.id).then((res) => {
      console.log(res)
      if (res && res.data && res.data.code === 1) {
        this.ruleForm = res.data.data
        this.ruleForm.status = res.data.data.status == '1'
        this.ruleForm.recommended = res.data.data.recommended == '1'
        ;(this.ruleForm as any).price = res.data.data.price
        // this.imageUrl = `http://172.17.2.120:8080/common/download?name=${res.data.data.image}`
        this.imageUrl = res.data.data.image
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }

  mounted() {}
  // 获取未被禁用材料和菜品分类
  private getDishList() {
    dishNoCategoryList({ type: 1 }).then((res) => {
      console.log(res)
      if (res.data.code === 1) {
        this.setMealList = res && res.data && res.data.data
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }
  private getDishCategoryList() {
    dishNoCategory({ type: 1 }).then((res) => {
      console.log(res)
      if (res.data.code === 1) {
        this.MealList = res && res.data && res.data.data
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }
  public submitForm(formName: any, st: any) {
    if (!this.ruleForm.image) return this.$message.error('菜品图片不能为空')
    this.ruleForm.price = parseFloat(this.ruleForm.price)
    this.ruleForm.defaultPrice = parseFloat(this.ruleForm.defaultPrice)
    // Convert boolean values to numbers
    this.ruleForm.status = this.ruleForm.status ? 1 : 0
    this.ruleForm.recommended = this.ruleForm.recommended ? 1 : 0
    this.ruleForm.dishInfoVOS.forEach((item) => {
      item.isMain = item.isMain ? 1 : 0
    })
    let prams = { ...this.ruleForm } as any
    if (this.actionType == 'add') {
      delete prams.id
      addDish(prams)
        .then((res) => {
          if (res && res.data && res.data.code === 1) {
            this.$message.success('材料添加成功！')
            if (!st) {
              this.$router.push({ path: '/dish' })
            } else {
              // Reset form fields if needed
              ;(this as any).$refs.ruleForm.resetFields()
              this.ruleForm = {
                id: '',
                name: '',
                price: '',
                defaultPrice: '',
                discount: '',
                image: '',
                description: '',
                status: true,
                recommended: true,
                dishInfoVOS: [
                  {
                    deleted: 0,
                    dishId: 0,
                    id: 0,
                    isMain: true,
                    materialNumber: 0,
                    materialId: 0,
                  },
                ],
              } as any
              this.imageUrl = ''
            }
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((err) => {
          this.$message.error('请求出错了：' + err.message)
        })
    } else {
      delete prams.updateTime
      editDish(prams)
        .then((res) => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success('材料修改成功！')
            this.$router.push({ path: '/dish' })
          } else {
            // this.$message.error(res.data.desc || res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error('请求出错了：' + err.message)
        })
    }
  }

  imageChange(value: any) {
    this.ruleForm.image = value
  }
}
</script>
<style lang="scss" scoped>
.addBrand-container {
  .el-form--inline .el-form-item__content {
    width: 293px;
  }

  .el-input {
    width: 350px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }

      .upload-item {
        .el-form-item__error {
          top: 90%;
        }
      }
    }
  }
}

.flavorBox {
  width: 777px;

  .addBut {
    background: #83a2ff;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
  }

  .flavor {
    border: solid 1px #dfe2e8;
    border-radius: 3px;
    padding: 15px;
    background: #fafafb;

    .title {
      color: #606168;

      .des-box {
        padding-left: 44px;
      }
    }

    .cont {
      .items {
        display: flex;
        margin: 10px 0;

        .itTit {
          width: 150px;
          margin-right: 15px;

          input {
            width: 100%;
            // line-height: 40px;
            // border-radius: 3px;
            // padding: 0 10px;
          }
        }

        .labItems {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          border-radius: 3px;
          min-height: 39px;
          border: solid 1px #d8dde3;
          background: #fff;
          padding: 0 5px;

          span {
            display: inline-block;
            color: #83a2ff;
            margin: 5px;
            line-height: 26px;
            padding: 0 10px;
            background: #fffbf0;
            border: 1px solid #fbe396;
            border-radius: 4px;
            font-size: 12px;

            i {
              cursor: pointer;
              font-style: normal;
            }
          }

          .inputBox {
            display: inline-block;
            width: 100%;
            height: 36px;
            line-height: 36px;
            overflow: hidden;
          }
        }

        .delFlavor {
          display: inline-block;
          padding: 0 10px;
          color: #83a2ff;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
